<template>
  <div class="role-page">
    <transition name="el-zoom-in-top">
      <el-form v-show="searchRoleVisible" inline size="mini" :model="searchRoleForm" ref="searchRoleForm"
               @keyup.enter.native="searchRoleHandle()">
        <el-form-item label="角色检索">
          <el-input v-model="searchRoleForm.word" clearable placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchRoleForm.roleKey" clearable placeholder="请输入角色键"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchRoleForm.status" clearable placeholder="请选择角色状态" class="role-status-input">
            <el-option label="可用" value="0"></el-option>
            <el-option label="不可用" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="dataLoad" @click="searchRoleHandle" type="primary"
                     icon="el-icon-search">查询</el-button>
          <el-button :disabled="dataLoad" @click="resetRolePageHandle" plain
                     icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="r-tool">
      <el-button :disabled="dataLoad"
                 @click="$refs.roleDialog.initRoleDialog(undefined, false)"
                 type="primary" size="mini" plain icon="el-icon-plus"
                 class="add-menu">添加</el-button>
      <el-button :disabled="dataLoad || roleTableSelected.length === 0" @click="deleteRoleHandle( undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete"
                 class="add-menu">删除</el-button>

      <right-tool-bar :search-visible="searchRoleVisible"
                      @toggle-search="searchRoleVisible = !searchRoleVisible" @refresh-table="getRoleList" />
    </div>

    <el-table
      v-loading="dataLoad"
      element-loading-text="角色数据加载中"
      element-loading-spinner="el-icon-loading"
      :data="roleList"
      :default-sort = "{ prop: searchRoleForm.field, order: searchRoleForm.order}"
      @sort-change="sortChangeHandle"
      @selection-change="val => this.roleTableSelected = val"
      ref="roleTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column sortable :sort-orders="sortOrders" prop="roleName" header-align="center" align="center"
                       label="角色名称">
      </el-table-column>
      <el-table-column sortable :sort-orders="sortOrders" prop="roleKey" header-align="center" align="center"
                       label="角色简称">
      </el-table-column>
      <el-table-column sortable :sort-orders="sortOrders" prop="sort" header-align="center" align="center"
                       label="排序等级">
        <template v-slot="scope">
          <el-tag type="info" class="r-sort">
            {{ scope.row.sort }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{scope.row.status === 0 ? '可用' : '不可用'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注" width="200"></el-table-column>
      <el-table-column sortable :sort-orders="sortOrders" prop="createTime" header-align="center" align="center"
                       label="创建时间" width="135">
      </el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建者"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template v-slot="scope">
          <el-button :disabled="scope.row.type === 2" type="text" icon="el-icon-s-operation"
                     @click="openRoleMenuModifyDialogHandle(scope.row)">授权</el-button>

          <el-dropdown :disabled="scope.row.type === 2 || loading">
            <span class="el-dropdown-link fz12" :style="{ color: themeColor, marginLeft: '7px' }">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-user"
                                @click.native="$refs.roleUserRelationDialog.init(scope.row, true)">
                查看用户
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 1" icon="el-icon-check" divided
                                @click.native="updateRoleStatusHandle(scope.row, 0)">
                使用
              </el-dropdown-item>
              <el-dropdown-item v-show="scope.row.status === 0" icon="el-icon-close" divided
                                @click.native="updateRoleStatusHandle(scope.row, 1)">
                禁用
              </el-dropdown-item>
              <el-dropdown-item divided icon="el-icon-edit"
                                @click.native="$refs.roleDialog.initRoleDialog(scope.row, true)">
                修改
              </el-dropdown-item>
              <el-dropdown-item icon="el-icon-delete" @click.native="deleteRoleHandle(scope.row)">
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页插件 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :disabled="dataLoad"
      :current-page="searchRoleForm.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="searchRoleForm.limit"
      :total="totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <!-- 角色 添加/修改 弹出框 -->
    <role-save-update ref="roleDialog" @close-dialog="closeRoleDialogHandle" />

    <!-- 角色授权弹出框 -->
    <role-menu-modify ref="roleMenuModifyDialog" />

    <!-- 角色关联用户弹出框 -->
    <role-user-relation ref="roleUserRelationDialog" />

  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar'
  import RoleSaveUpdate from "@/components/role/save-update";
  import roleMenuModify from "@/components/role/role-menu/modify.vue";
  import RoleUserRelation from "@/components/role/role-user/relation"

  export default {
    layout: 'admin',
    name: "admin-system-role",
    components: { RoleSaveUpdate, RightToolBar, roleMenuModify, RoleUserRelation },
    data() {
      return {
        // 客户端初始化
        clientInit: true,
        // 角色数据列表
        roleList: [],
        // 当前博客数量
        totalNum: undefined,
        // 角色表格被选中的‘行’数据
        roleTableSelected: [],
        // 表格排序字段排序方式
        sortOrders: ['ascending', 'descending'],
        // 角色检索表单对象
        searchRoleForm: {
          // 角色名称
          word: '',
          // 角色键
          roleKey: '',
          // 角色状态
          status: undefined,
          // 排序字段
          field: 'sort',
          // 排序方式
          order: 'ascending',
          // 页码
          page: 1,
          // 每页大小
          limit: 10
        },
        // 角色检索是否显示
        searchRoleVisible: true,
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 10,
        // 角色弹出框是否显示
        roleDialog: false,
        // 角色授权弹出框是否显示[true-显示 false-关闭]
        roleMenuModifyDialog: false,

      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    async asyncData({ app, params, error }) {
      // 客户端调用直接返回
      if (process.client) return {}
      let searchForm = {
        field: 'sort',
        order: 'ascending',
        page: 1,
        limit: 10
      }
      let res
      try {
        res = await app.$axios.$post('/sys/role/page/list', searchForm)
      } catch (e) {
        error(e.msg || '网络异常，请求失败')
        return {}
      }
      const data = res.data

      return {
        clientInit: false,
        roleList: data.list,
        totalNum: data.totalNum
      }
    },
    created() {
      if (process.client) {
        if (this.clientInit) {
          this.getRoleList()
        }
      }
    },
    methods: {
      /**
       * 角色检索事件
       */
      searchRoleHandle() {
        this.searchRoleForm.page = 1

        this.getRoleList()
      },
      /**
       * 获取角色数据列表事件
       */
      getRoleList() {
        let searchRoleForm = this.searchRoleForm
        // 表格数据加载
        this.dataLoad = true
        this.$axios.$post('/sys/role/page/list', searchRoleForm)
          .then(({ data:page }) => {
            this.roleList = page.list
            this.totalNum = page.totalNum
          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            this.dataLoad = false
          })
      },
      // 每页显示个数变化事件
      sizeChangeHandle(size) {
        this.searchRoleForm.page = 1
        this.searchRoleForm.limit = size
        this.getRoleList()
      },
      // '点击特定页码'、'上一页'、'下一页'操作事件
      currentChangeHandle(index) {
        if (this.searchRoleForm.page === index) {
          return
        }
        this.searchRoleForm.page = index
        this.getRoleList()
      },
      // 表格选择字段排序事件
      sortChangeHandle( { prop, order } ) {
        this.searchRoleForm.page = 1
        this.searchRoleForm.field = prop
        this.searchRoleForm.order = order

        this.getRoleList()
      },
      // 打开角色操作弹出框事件
      openRoleDialogHandle(role, optType) {
        this.roleDialog = true

        this.$nextTick(() => {
          this.$refs.roleDialog.initRoleDialog(this.searchRoleForm.deptId, this.deptName, role, optType)
        })
      },
      // 关闭角色操作弹出框事件
      closeRoleDialogHandle(bool) {
        this.roleDialog = false

        if (bool) {
          this.getRoleList()
        }
      },
      /**
       * 打开角色授权弹出框事件
       * @param {Object} role 角色对象
       */
      openRoleMenuModifyDialogHandle(role) {
        this.roleMenuModifyDialog = true

        this.$nextTick(() => {
          this.$refs.roleMenuModifyDialog.initRoleMenuModifyDialog(role.roleId)
        })
      },
      /**
       * 更新角色状态事件
       * @param {Object} role   角色对象
       * @param {Number} status 最新状态
       */
      updateRoleStatusHandle(role, status) {
        // 按钮不可被点击
        this.buttonLoad = true;
        this.$axios.$post('/sys/role/update/status', { roleId: role.roleId, status: status })
          .then(() => {
            // 变更角色状态
            role.status = status;
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false;
          })
      },
      /**
       * 删除角色事件
       * @param {Object} role 角色对象（只有单个删除时，该参数才有值）
       */
      deleteRoleHandle(role) {
        // 所有要删除的角色id
        let roleIds = []
        // 所有要删除的角色名字
        let roleNames = []
        if (!role) {
          for (let role of this.roleTableSelected) {
            if (role.type === 2) {
              this.notify('', '操作提示', '选中角色包含系统角色，操作被拒绝');
              return;
            }
            roleIds.push(role.roleId)
            roleNames.push(role.roleName)
          }
        } else {
          roleIds.push(role.roleId)
          roleNames.push(role.roleName)
        }
        this.$confirm(`确定删除[${roleNames}]角色吗?`, '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          this.$axios.$delete('/sys/role/delete', { data: roleIds})
            .then(() => {
              this.notify('success', '操作成功', `${roleNames}角色删除成功`)

              // 清空表格选中行
              // this.$refs.roleTable.clearSelection()
              // 重新获取角色列表
              this.getRoleList()
            })
            .catch(() => {})
        }).catch(() => {})
      },
      // 重置页面事件
      resetRolePageHandle() {
        // 重置角色查询表单
        this.$refs['searchRoleForm'].resetFields()
        this.searchRoleForm.page = 1
        this.searchRoleForm.limit = 10

        this.getRoleList()
      }
    }
  }
</script>

<style scoped>
  .role-page .dept-content > div:first-child {
    margin-bottom: 7px;
  }
  .role-page .role-status-input {
    width: 140px;
  }
  .role-page .r-tool {
    margin-bottom: 7px;
  }
  .role-page .paging {
    float: right;
    margin: 7px;
  }
  .role-page .r-sort {
    color: black;
  }
</style>
